package com.hot100;

import java.util.Comparator;
import java.util.PriorityQueue;
@SuppressWarnings("all")
public class h023 {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists.length == 0) return null;

        ListNode head = new ListNode(0);
        ListNode last = head;
        PriorityQueue<ListNode> priorityQueue = new PriorityQueue<>(new Comparator<ListNode>() {
            @Override
            public int compare(ListNode o1, ListNode o2) {
                return o1.val - o2.val;
            }
        });

        for (int i = 0;i<lists.length;i++){
            priorityQueue.offer(lists[i]);
        }

        while (!priorityQueue.isEmpty()){
            ListNode min = priorityQueue.poll();
            last.next = min;
            last = last.next;
            priorityQueue.offer(min.next);
        }

        return head.next;
    }
}
